/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dropbinconnect.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author LegACy
 */
public class Connect {
	protected static int s_Port = 10000;

	//No constructor
	protected Connect() {}

	protected static Socket sendRequest(int action, JSONObject request) throws IOException {
		//Create socket
		Socket Sock = new Socket(InetAddress.getLocalHost(), s_Port);

		//Create message
		String Message = "";
		Message += (char) action;
		Message += request.toString();

		//Send message
		PrintWriter Writer = new PrintWriter(Sock.getOutputStream());
		Writer.println(Message);
		Writer.flush();

		//Return the socket
		return Sock;
	}

	public static boolean login(String username, String password) throws Exception {
		//Initial
		boolean Result = false;

		try {
			//Create JSON
			JSONObject Request = new JSONObject();
			Request.put("username", username);
			Request.put("password", password);
			try {
				//Send request
				Socket Sock = sendRequest(Protocol.ACTION_LOGIN, Request);

				//Create reader
				BufferedReader Reader = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
				
				//Read action
				int Answer = Reader.read();
				if (Answer == Protocol.ACTION_LOGIN + Protocol.RESPONSE_OFFSET) {
					//Read response
					JSONObject Response = new JSONObject(Reader.readLine());
					Result				= Response.getBoolean("result");

					//If error, exception
					if (!Result) throw new Exception(Response.getString("reason"));
				} else throw new Exception("Response error");

				//Close socket
				Sock.close();
			} catch (IOException ex) {
				throw new Exception("Connection error");
			}
		} catch (JSONException ex) {
			throw new Exception("JSON Error");
		}

		//Return
		return Result;
	}

	public static int getLatest(String username) throws Exception {
		//Initial
		int Result = 0;

		//Return
		return Result;
	}

	public static JSONArray getStructure(String username, int version) throws Exception {
		//Initial
		JSONArray Result = new JSONArray();

		//Return
		return Result;
	}

	public static String getFile(String username, int version, String path) throws Exception {
		//Initial
		String Result = "";

		//Return
		return Result;
	}
}